﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using ChatApp.Client.Common;
using ChatApp.Client.ChatAppServiceReference;
using System.ServiceModel;
using System.Linq;
using DevExpress.Xpf.Grid;
using DevExpress.Xpf.Docking;
using System.Collections.Generic;
using System.Windows.Media.Imaging;

namespace ChatApp.Client
{
    /// <summary>
    /// Interaction logic for ucListChat.xaml
    /// </summary>
    public partial class ucListChat : UserControl, IChatAppServiceCallback
    {
        public ucListChat()
        {
            InitializeComponent();
            ChatAppServiceClient client = new ChatAppServiceClient(new InstanceContext(this));
            //Đăng ký Enpoint User
            client.RegisterClient(ChatAppGlobal.UserLogin.UserName);
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            txtTenDangNhap.Padding = new Thickness(35, 0, 0, 0);
            txtTenDangNhap.IsEnabled = false;
        }

        public void BindListDanhSachBanBe()
        {
            gridDanhSachBanBe.ItemsSource = null;
            gridDanhSachBanBe.ItemsSource = ChatAppGlobal.ListAddFriend;
        }

        private void btnThemBan_Click(object sender, RoutedEventArgs e)
        {
            ThemBan formThemban = new ThemBan();
            formThemban.Show();
        }

        private void gridDanhSachBanBe_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (gridDanhSachBanBe.View.GetRowHandleByMouseEventArgs(e) != GridControl.InvalidRowHandle)
            {
                AddFriend addFriend = gridDanhSachBanBe.GetFocusedRow() as AddFriend;
                
                // Nếu chọn người chát không đúng thì kết thúc xử lý
                if (addFriend == null)
                    return;

                // Kiểm tra không tồn tại trong danh sách những người mình đang chát
                if (ChatAppGlobal.ListTabChat.FirstOrDefault(u => u.Name == addFriend.User1.UserName) == null)
                {
                    (ChatAppGlobal.FormMainWindow as MainWindow).ShowUserControl(addFriend.User1.UserName
                                                                                , 0
                                                                                , false
                                                                                , new List<string> 
                                                                                            { 
                                                                                                ChatAppGlobal.UserLogin.UserName,
                                                                                                addFriend.User1.UserName
                                                                                            }
                                                                                , false
                                                                                );
                }
                else
                {
                    LayoutPanel layoutPanel;
                    DockLayoutManager dockLayoutManagerMain = (ChatAppGlobal.FormMainWindow as MainWindow).dockLayoutManagerMain;
                    TabbedGroup tabbedGroupExisting = dockLayoutManagerMain.LayoutRoot.Items.FirstOrDefault() as TabbedGroup;
                    if (tabbedGroupExisting != null)
                    {
                        layoutPanel = tabbedGroupExisting.Items.Where(u => u.Name == addFriend.User1.UserName).FirstOrDefault() as LayoutPanel;
                        tabbedGroupExisting.SelectedTabIndex = tabbedGroupExisting.Items.IndexOf(layoutPanel);
                    }
                }

                // Tìm kiếm lại tab vừa add
                LayoutPanel LayoutPanelChat = ChatAppGlobal.ListTabChat.FirstOrDefault(u => u.Name == addFriend.User1.UserName) as LayoutPanel;

                // Lấy UserControl chát bên trong
                ucChat chatControl = LayoutPanelChat.Control as ucChat;

                // Chọn đến chỗ nhập
                chatControl.txtNoidung.Focus();
            }
        }

        private void gridDanhSachBanBe_PreviewKeyDown(object sender, KeyEventArgs e)
        {

        }

        public void RefreshContentChat(int idRoom, string tenRoom, string userNameSend, string textChat, bool laChatRoom)
        {
            LayoutPanel LayoutPanelChat = null;
            // Nếu là chát thường
            if (!laChatRoom)
            {
                // Trường hợp là Refresh chính nó
                if (userNameSend == ChatAppGlobal.UserLogin.UserName)
                {
                    LayoutPanelChat = ChatAppGlobal.ListTabChat.FirstOrDefault(u => u.Name == tenRoom) as LayoutPanel;
                }
                else // Trường hợp Refresh người dùng khác khác mình
                {
                    LayoutPanelChat = ChatAppGlobal.ListTabChat.FirstOrDefault(u => u.Name == userNameSend) as LayoutPanel;
                    // Nếu chưa có tab
                    if (LayoutPanelChat == null)
                    {
                        // Add Tab
                        (ChatAppGlobal.FormMainWindow as MainWindow).ShowUserControl(userNameSend
                                                                                , idRoom
                                                                                , false
                                                                                , new List<string> 
                                                                                            { 
                                                                                                ChatAppGlobal.UserLogin.UserName,
                                                                                                userNameSend
                                                                                            }
                                                                                , true
                                                                                );
                        // Tìm kiếm lại tab vừa add
                        LayoutPanelChat = ChatAppGlobal.ListTabChat.FirstOrDefault(u => u.Name == userNameSend) as LayoutPanel;
                    }
                    else
                    {
                        // Thiết lập Icon có message mới
                        BitmapImage img = new BitmapImage();
                        img.BeginInit();
                        img.UriSource = new Uri(@"pack://application:,,,/ChatApp.Client;component/Images/Icons/chat.png");
                        img.EndInit();
                        LayoutPanelChat.CaptionImage = img;
                    }
                }

                if (LayoutPanelChat != null)
                {
                    // Lấy UserControl chát bên trong
                    ucChat chatControl = LayoutPanelChat.Control as ucChat;
                    //Add nội dung chát
                    chatControl.AddContentChat(new ViewContentChat { ContentChat = textChat });
                }
            }
        }
    }
}
